<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
        private  $_id;
        public function authenticate()
        {
                $user = Users::model()->findByAttributes(array('username'=>$this->username));
                if ($user === null) {
                        $this->errorCode = self::ERROR_USERNAME_INVALID;
                        Yii::app()->user->setFlash('error', "Username or password is incorrect.");
                } else {
                        if ($user->password !== $this->password){
                                Yii::app()->user->setFlash('error', "Username or password is incorrect.");
                                $this->errorCode = self::ERROR_PASSWORD_INVALID;
                        }
                        else {
                                if($user->activation == 1){
                                        $this->_id = $user->id;
                                        // phan quyen   
                                        $auth=Yii::app()->authManager; //initializes the authManager
                                        if(!$auth->isAssigned($user->role,$this->_id)) //checks if the role for this user has already been assigned and if it is NOT than it returns true and continues with assigning it below
                                        {
                                            if($auth->assign($user->role,$this->_id)) //assigns the role to the user
                                            {
                                                Yii::app()->authManager->save(); //saves the above declaration
                                            }           
                                        } 
                                        // end phan quyen
                                             
                                        if (null === $user->lastvisitDate)
                                                $lastLogin = time();
                                        else
                                                $lastLogin = strtotime($user->lastvisitDate);
                                        $this->setState('lastvisitDate', $lastLogin);
                                        $this->errorCode = self::ERROR_NONE;
                                }else{
                                        $this->errorCode = 100;
                                }
                        }
                }
                return $this->errorCode;
        }
        public function getId() {
                return $this->_id;
        }
}